﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Security.Cryptography;

namespace Global
{
    public class Functions
    {
        #region 程序集特性访问器

        public string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        public string AssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        public string AssemblyDescription
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyDescriptionAttribute)attributes[0]).Description;
            }
        }

        public static string AssemblyProduct
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyProductAttribute)attributes[0]).Product;
            }
        }

        public string AssemblyCopyright
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            }
        }

        public static string AssemblyCompany
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCompanyAttribute)attributes[0]).Company;
            }
        }
        #endregion

        #region 写入日志方法
        static bool m_isAccessDenied = false;
        #region // LOG(string log)
        /// <summary>
        /// 记录日志,显示分秒毫秒
        /// </summary>
        /// <param name="log">内容</param>
        public static void LOG(string log)
        {
            //if (m_isAccessDenied) return;

            //string userAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string _commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            //string appPath = Application.ExecutablePath;
            //string userFolder = Application.LocalUserAppDataPath;
            //string version = Application.ProductVersion;
            string _company = AssemblyCompany;
            string _appName = AssemblyProduct;
            string _logDirectory = _commonAppData + "\\" + _company + "\\" + _appName;
            if (!Directory.Exists(_logDirectory))
            {
                Directory.CreateDirectory(_logDirectory);
            }

            //log = DateTime.Now.Minute.ToString().PadLeft(2, '0') + ":"
            //     + DateTime.Now.Second.ToString().PadLeft(2, '0') + "."
            //     + DateTime.Now.Millisecond.ToString().PadLeft(3, '0')
            //     + "  [" + ServiceProvider.nameCurrentClass + "] "
            //     + log;

            log = string.Format("{0:D2}:{1:D2}.{2:D3}", DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond)
                + "  [" + ServiceProvider.nameCurrentClass + "] "
                 + log;
            try
            {
                FileStream _stream = File.Open(_logDirectory + "\\log.txt", FileMode.Append);
                StreamWriter _writer = new StreamWriter(_stream);
                Console.WriteLine(log);
                _writer.WriteLine(log);
                _writer.Close();
                _stream.Close();
            }
            catch (Exception Ex)
            {
                Debug.Print(Ex.Message);
                m_isAccessDenied = true;
                return;
            }
        }
        #endregion

        #region // LOG(string className, string log)
        /// <summary>
        /// 记录日志,显示分秒毫秒
        /// </summary>
        /// <param name="className">类名</param>
        /// <param name="log">日志内容</param>
        public static void LOG(string className, string log)
        {
            if (m_isAccessDenied) return;
            //string userAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string _commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            //string appPath = Application.ExecutablePath;
            //string userFolder = Application.LocalUserAppDataPath;
            //string version = Application.ProductVersion;
            string _company = AssemblyCompany;
            string _appName = AssemblyProduct;
            string _logDirectory = _commonAppData + "\\" + _company + "\\" + _appName;
            if (!Directory.Exists(_logDirectory))
            {
                Directory.CreateDirectory(_logDirectory);
            }

            //log = DateTime.Now.Minute.ToString().PadLeft(2, '0') + ":"
            //     + DateTime.Now.Second.ToString().PadLeft(2, '0') + "."
            //     + DateTime.Now.Millisecond.ToString().PadLeft(3, '0')
            //     + "  [" + className + "] "
            //     + log;
            log = string.Format("{0:D2}:{1:D2}.{2:D3}", DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond)
                + "  [" + className + "] "
                 + log;
            try
            {
                FileStream _stream = File.Open(_logDirectory + "\\log.txt", FileMode.Append);
                StreamWriter _writer = new StreamWriter(_stream);
                Console.WriteLine(log);
                _writer.WriteLine(log);
                _writer.Close();
                _stream.Close();
            }
            catch (Exception Ex)
            {
                Debug.Print(Ex.Message);
                m_isAccessDenied = true;
                return;
            }
        }
        #endregion

        #region // LOG(DateTime timestamp, string log)
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <param name="log">日志内容</param>
        public static void LOG(DateTime timestamp, string log)
        {
            //string userAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string _commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            //string appPath = Application.ExecutablePath;
            //string userFolder = Application.LocalUserAppDataPath;
            //string version = Application.ProductVersion;
            string _company = AssemblyCompany;
            string _appName = AssemblyProduct;
            string _logDirectory = _commonAppData + "\\" + _company + "\\" + _appName;
            string _logPath = _logDirectory + "\\log.txt";

            #region // if file size is large than 1MB set it as back up
            if (File.Exists(_logPath))
            {
                // Create new FileInfo object and get the Length.
                FileInfo _fileInfo = new FileInfo(_logPath);
                // if file size is large than 1MB set it as back up
                if (_fileInfo.Length > 1000000 && log == "App started!")
                {
                    DateTime _lastWrite = _fileInfo.LastWriteTime;
                    string _backFile = _lastWrite.ToString("yyyyMMddhhmmss");
                    _backFile = _logDirectory + "\\" + _backFile + ".bak";
                    try
                    {
                        File.Move(_fileInfo.FullName, _backFile);
                    }
                    catch (Exception Ex)
                    {
                        //MessageBox.Show(
                        //    Ex.Message
                        //    , "Error"
                        //    , MessageBoxButtons.OK
                        //    , MessageBoxIcon.Exclamation);

                        Debug.Print(Ex.Message);
                        m_isAccessDenied = true;
                        return;
                    }
                }
            }
            #endregion

            if (!Directory.Exists(_logDirectory))
            {
                Directory.CreateDirectory(_logDirectory);
            }
            try
            {
                log = "\n" + timestamp + "  " + log;
                FileStream _stream = File.Open(_logPath, FileMode.Append);
                StreamWriter _writer = new StreamWriter(_stream);
                Console.WriteLine(log);
                _writer.WriteLine(log);
                if (log.Contains("End")) _writer.WriteLine("");
                _writer.Close();
                _stream.Close();
            }
            catch (Exception Ex)
            {
                Debug.Print(Ex.Message);
                m_isAccessDenied = true;
                return;
            }
        }
        #endregion
        #endregion

        #region 加解密
        //默认密钥向量     
        private static byte[] Keys = { 0x11, 0x24, 0x66, 0x18, 0x9A, 0xDB, 0xDF, 0xAF };
        //默认密钥
        private static string mKey="plhtplht";

        /// <summary> 
        ///DES加密字符串 
        ///</summary>     
        ///<param name="encryptString">待加密的字符串</param>   
        ///<param name="encryptKey">加密密钥,要求为8位</param> 
        ///<returns>加密成功返回加密后的字符串，失败返回空字符串</returns>  
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns>加密成功返回加密后的字符串，失败返回空字符串</returns>
        public static string EncryptDES(string encryptString)
        {
            return  EncryptDES(encryptString, mKey);
        }
        /// <summary>   
        ///  DES解密字符串   
        ///</summary>   
        ///<param name="decryptString">待解密的字符串</param>
        ///<param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        ///<returns>解密成功返回解密后的字符串，失败返回空字符串</returns> 
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">带解密字符串</param>
        /// <returns>解密成功返回解密后的字符串，失败返回空字符串</returns>
        public static string DecryptDES(string decryptString)
        {
            return DecryptDES(decryptString);
        }
        #endregion
    }
}
